#!/bin/bash

# Configuration variables
AUTHORS_FILE="authors.txt"
TEMP_REPO_DIR="svn-temp-repo"
LOG_FILE="migration_$(date +%Y%m%d_%H%M%S).log"

# Function to log messages
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Function to log and execute commands
log_and_execute() {
    local cmd="$1"
    local description="$2"
    
    log_message "=== Executing: $description ==="
    log_message "Command: $cmd"
    echo "Executing: $description"
    echo "Command: $cmd"
    
    if eval "$cmd"; then
        log_message "SUCCESS: $description completed successfully"
        echo "SUCCESS: $description completed successfully"
        return 0
    else
        log_message "ERROR: $description failed with exit code $?"
        echo "ERROR: $description failed with exit code $?"
        return 1
    fi
}

# Function to get user input
get_user_input() {
    local prompt="$1"
    local var_name="$2"
    local default_value="$3"
    
    if [ -n "$default_value" ]; then
        read -p "$prompt [$default_value]: " input
        if [ -z "$input" ]; then
            input="$default_value"
        fi
    else
        read -p "$prompt: " input
        while [ -z "$input" ]; do
            echo "Error: This field cannot be empty."
            read -p "$prompt: " input
        done
    fi
    
    eval "$var_name=\"$input\""
}

# Log script version and environment info
SCRIPT_VERSION="1.1"
SCRIPT_AUTHOR="Migration Script Maintainer"
log_message "=== SVN to Git Migration Started ==="
log_message "Script: $0"
log_message "Script Version: $SCRIPT_VERSION"
log_message "Script Author: $SCRIPT_AUTHOR"
log_message "Working directory: $(pwd)"
log_message "Log file: $LOG_FILE"
log_message "System Info: $(uname -a)"
log_message "Git Version: $(git --version)"
log_message "Bash Version: $BASH_VERSION"

# authors.txt file summary
if [ -f "$AUTHORS_FILE" ]; then
    AUTHOR_LINES=$(wc -l < "$AUTHORS_FILE")
    AUTHOR_MD5=$(md5sum "$AUTHORS_FILE" | awk '{print $1}')
    log_message "Authors File: $AUTHORS_FILE (Lines: $AUTHOR_LINES, MD5: $AUTHOR_MD5)"
else
    log_message "Authors File: $AUTHORS_FILE (Not Found)"
fi

# Get source SVN repository URL
get_user_input "Please enter the source SVN repository URL" "SVN_REPO_URL"

# Get target Git repository URL
get_user_input "Please enter the target Git repository URL" "GIT_REPO_URL"

# Confirm migration parameters

echo ""
echo "Migration Parameters:"
echo "Source SVN Repository: $SVN_REPO_URL"
echo "Target Git Repository: $GIT_REPO_URL"
echo "Authors File: $AUTHORS_FILE"
echo "Log File: $LOG_FILE"
echo ""

read -p "Do you want to proceed with the migration? (y/N): " confirm
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    log_message "Migration cancelled by user."
    echo "Migration cancelled."
    exit 0
fi

# Check if authors file exists
if [ ! -f "$AUTHORS_FILE" ]; then
    log_message "ERROR: Authors file '$AUTHORS_FILE' not found."
    echo "ERROR: Authors file '$AUTHORS_FILE' not found. Please create it before running the migration."
    exit 1
fi

# Check if temp directory already exists
if [ -d "$TEMP_REPO_DIR" ]; then
    log_message "WARNING: Temporary directory '$TEMP_REPO_DIR' already exists."
    read -p "Temporary directory '$TEMP_REPO_DIR' already exists. Remove it? (y/N): " remove_temp
    if [[ "$remove_temp" =~ ^[Yy]$ ]]; then
        log_message "Removing existing temporary directory..."
        log_and_execute "rm -rf \"$TEMP_REPO_DIR\"" "Remove existing temporary directory"
    else
        log_message "ERROR: Cannot proceed with existing temporary directory."
        echo "ERROR: Cannot proceed with existing temporary directory. Please remove it manually or choose to remove it."
        exit 1
    fi
fi

# 1. Clone SVN repository
log_message "=== Step 1: Clone SVN Repository ==="
echo "Step 1: Cloning SVN repository..."

svn_clone_cmd="git svn clone --stdlayout --no-metadata -A \"$AUTHORS_FILE\" \"$SVN_REPO_URL\" \"$TEMP_REPO_DIR\""
if log_and_execute "$svn_clone_cmd" "Clone SVN repository"; then
    log_message "SVN repository cloned successfully."
    echo "SVN repository cloned successfully."
    log_message "Local branches before migration: $(git branch)"
else
    log_message "ERROR: Failed to clone SVN repository."
    echo "ERROR: Failed to clone SVN repository. Please check the URL and try again."
    exit 1
fi

# 2. Enter temporary repository directory
log_message "=== Step 2: Enter Temporary Repository Directory ==="
echo "Step 2: Entering temporary repository directory..."

cd_cmd="cd \"$TEMP_REPO_DIR\""
if log_and_execute "$cd_cmd" "Change to temporary repository directory"; then
    log_message "Successfully entered temporary repository directory."
    echo "Successfully entered temporary repository directory."
else
    log_message "ERROR: Failed to enter temporary repository directory."
    echo "ERROR: Failed to enter temporary repository directory."
    exit 1
fi

# 3. Create local branches corresponding to remote branches (excluding trunk and tags)
log_message "=== Step 3: Create Local Branches ==="
echo "Step 3: Creating local branches..."

branch_list_cmd="git branch -r | grep -vE \"trunk|tags/\""
log_message "Command to get remote branches: $branch_list_cmd"
remote_branches=$(eval "$branch_list_cmd")
log_message "Remote branches found: $remote_branches"

branch_count=0
for branch in $remote_branches; do
    local_name=${branch#origin/}
    branch_cmd="git branch \"$local_name\" \"$branch\""
    if log_and_execute "$branch_cmd" "Create local branch: $local_name from $branch"; then
        log_message "Created local branch: $local_name"
        echo "Created local branch: $local_name"
        ((branch_count++))
    else
        log_message "WARNING: Failed to create local branch: $local_name"
        echo "WARNING: Failed to create local branch: $local_name"
    fi

done
log_message "Created $branch_count local branches."

# 4. Add Git remote repository
log_message "=== Step 4: Add Git Remote Repository ==="
echo "Step 4: Adding Git remote repository..."

remote_add_cmd="git remote add gitee \"$GIT_REPO_URL\""
if log_and_execute "$remote_add_cmd" "Add Git remote repository"; then
    log_message "Git remote repository added successfully."
    echo "Git remote repository added successfully."
else
    log_message "ERROR: Failed to add Git remote repository."
    echo "ERROR: Failed to add Git remote repository. Please check the URL."
    exit 1
fi

# 5. Push all branches to Git repository
log_message "=== Step 5: Push All Branches to Git Repository ==="
echo "Step 5: Pushing all branches to Git repository..."

push_cmd="git push gitee --all"
if log_and_execute "$push_cmd" "Push all branches to Git repository"; then
    log_message "All branches pushed successfully to Git repository."
    echo "All branches pushed successfully to Git repository."
    log_message "Local branches after migration: $(git branch)"
    log_message "Remote branches after migration: $(git branch -r)"
else
    log_message "ERROR: Failed to push branches to Git repository."
    echo "ERROR: Failed to push branches to Git repository. Please check the repository URL and permissions."
    exit 1
fi

# 6. Clean up temporary directory
log_message "=== Step 6: Clean Up Temporary Directory ==="
echo "Step 6: Cleaning up temporary directory..."

cd_cmd_back="cd .."
log_and_execute "$cd_cmd_back" "Return to original directory"

cleanup_cmd="rm -rf \"$TEMP_REPO_DIR\""
if log_and_execute "$cleanup_cmd" "Remove temporary directory"; then
    log_message "Temporary directory cleaned up successfully."
    echo "Temporary directory cleaned up successfully."
else
    log_message "WARNING: Failed to clean up temporary directory."
    echo "WARNING: Failed to clean up temporary directory. You may need to remove it manually."
fi

# Migration completed
log_message "=== SVN to Git Migration Completed Successfully ==="
log_message "Migration Summary:"
log_message "Source repository: $SVN_REPO_URL"
log_message "Target repository: $GIT_REPO_URL"
log_message "Authors File: $AUTHORS_FILE (Lines: $AUTHOR_LINES, MD5: $AUTHOR_MD5)"
log_message "Local branches: $(git branch)"
log_message "Remote branches: $(git branch -r)"
LOG_SIZE=$(du -h "$LOG_FILE" | awk '{print $1}')
log_message "Log file size: $LOG_SIZE"
echo ""
echo "Migration completed successfully!"
echo "Log file: $LOG_FILE"
echo "Source repository: $SVN_REPO_URL"
echo "Target repository: $GIT_REPO_URL"